/**
 * 广告列表
 */
define(['../../common/service'],function(http){
   var AdList = {
   		init: function () {
            var _this = this;
			//列表管理
			$('[list-manager="ad-list"]').listManager('init', {
				isRealTime:true
				,setTopVal:$('[list-manager="ad-list"]').offset().top//调整吸顶的高度,需要减去这个高度
				,scrollDOM:$('.fmp-article')//监听滚动条
				,supportAjaxPage: true		//是否支持配置列表ajxa分页[多列表两种状态都有时，统一配置为true,禁用的列表pageJson参数为空即可]
				,pageCallback:function(query){
					_this._initAdList(query);
				}
			}, function(query){
				_this._initAdList(query);
			});
			_this.bindRetry();
        }
	   ,bomm: function(){
		   console.log(this)
		   delete this
	   }
	   ,getThis: function(){
		console.log(this)
	}
		/*
			@初始化广告发布列表
		*/
        ,_initAdList: function(query){
            var _this = this;
            var loadingArea = $('.container-fluid');
            Kit.loading.show(loadingArea);
            http.work('/publishbatchs/searchAllPublishBatch',query,'POST').then(function(res){
            	if(res.flag == 'success'){
            		var tmpHtml = '',
					_list = res.data.publishBatchs,
					_paginator = res.data.paginator,
					_table = $('table[list-manager="ad-list"]'),
					_tbody = $('.publish-batch-list', _table),
					_serial = 0;		//序号
					for(var i=0; i< _list.length; i++){
						_serial = (_paginator.cPage-1) * _paginator.pSize +i + 1;
						tmpHtml += _this.generateHTML(_list[i],_serial);
					}
					_tbody.html(tmpHtml);
					_table.listManager([{'resetTd':false, 'resetPageData': _paginator}]);
					$(window).trigger('resize');
					//实时更新广告发布状态
					_this.updataState();
            	}else{
            		Kit.alert2(res.msg || '操作失败')
            	}
				Kit.loading.hide(loadingArea);
            });
        }
		/*
			@实时更新广告发布状态
		*/
		,updataState: function(){
			var _this = this;
			var _tbody = $('.publish-batch-list'),
				ongoingList = _tbody.find('.p-waiting, .p-ongoing');
			if(ongoingList.length == 0){
				_this.bindOpenDetail();
				console.log('当前数据已全部发布成功，实时更新功能已中止');
				window.clearTimeout(_this.stoupdataState);
				return false;
			}
			console.log('当前共有['+ongoingList.length+']条数据需要实时更新');

			var batchIds = [];
			for(var i=0; i<ongoingList.length; i++){
				batchIds.push(ongoingList.eq(i).attr('batch-id'));
			}
            http.work('/publishbatchs/searchPublishBatchByIds',batchIds,'POST').then(function(res){
				var tmpHtml = '',
					_list = res.data.publishBatchs,
					_tbody = $('.publish-batch-list'),
					_tr,
					_newTr,
					_serial = 0,		//序号
					_trIndex;
				if(!_list || _list.length == 0){
					console.log('返回数据为空，已跳出对列表区域DOM节点的渲染');
					return false;
				}
				for(var i=0; i< _list.length; i++){
					_tr = _tbody.find('tr[batch-id="'+_list[i].id+'"]');
					if(!_tr || _tr.length != 0){ //??
						_serial = _tr.find('.serial').text();
						tmpHtml = _this.generateHTML(_list[i], _serial);
						_newTr = $(tmpHtml).hide();
						_tbody.append(_newTr);
						_newTr.listManager('resetTd', true);
						_tr.replaceWith(_newTr);
						_newTr.show();
						_tr.remove();
					}
				}
				_this.bindOpenDetail();

            });
			//定时刷新数据
			_this.stoupdataState = window.setTimeout(function(){
				_this.updataState();
			},5000);
		}
		/*
			@生成HTML
		*/
		,generateHTML: function(obj,_serial){
			var _this = this;
            // delete by sisi  for 预算优化 出价与预算相对应
//			var budgetHtml 	= '', //预算出价
		    var timeHtml 	= '', //排程
				tmpHtml 	= '', //单条数据
				statusClass = ''; //发布状态使用className

//			budgetHtml = (obj.dailyBudget != 0
//						? ('日预算：'+obj.dailyBudget / 100)
//						: ('总预算：'+obj.lifetimeBudget / 100));
			timeHtml=  obj.startTime
					+ '&nbsp;~&nbsp;'
					+ (obj.endTime != '' ? obj.endTime : I18N.getText('adList','ongoing'));



			//发布状态：0、待发布  1、正在发布 2、发布成功 3、发布失败 5、重试中
			//对应class: 0、waiting 1、ongoing 2、success 3、error
			if(obj.publishStatus == 0||obj.publishStatus == 10){
				statusClass = 'p-waiting';
			}
			if(obj.publishStatus == 1||obj.publishStatus == 11){
				statusClass = 'p-ongoing';
			}
			if(obj.publishStatus == 2){
				statusClass = 'p-success';
			}
			if(obj.publishStatus == 3){
				statusClass = 'p-error';
			}
			if(obj.publishStatus == 5){
				statusClass = 'p-ongoing';
			}
		   tmpHtml += '<tr batch-id="'+obj.id+'" class="'+statusClass+'" batch-status="'+(obj.publishStatus || '')+'">'
			   + '<td class="serial number-show" >'
			   + (_serial || '')
			   + '</td>'
			   + '<td title="'+obj.objectName+'" class="text-left number-show">'
			   + '<a target="_blank" href="javascript:void(0)" data-href="#!adDetail?id='+obj.id+'" class="number-show btn-link">'
			   + '<span class="publishBatchName">'
			   + obj.objectName
			   + '</span>'
			   + '</a>';
			if(obj.publishStatus == 3 && obj.retryCnt <3) {
				tmpHtml +=  '<span class="glyphicon glyphicon-repeat icon-btn" style="cursor: pointer;margin-left:10px;" ' +
					'title="' + I18N.getText('adList','failedRetry') + '"></span>';
			}
			tmpHtml += '<span class="loadingbatch get-loading-style2"></span>';
		    //营销活动显示
		    var campaignNameShow = (obj.campaignCount || 0) + '/' + (obj.allCampaignCount || 0);
		   if (obj.campaignName && obj.campaignName != ""){
			   campaignNameShow = obj.campaignName + '(' + campaignNameShow + ')';
		   }
		   //广告系列显示
		   var adsetNameShow = (obj.adSetCount || 0) + '/' + (obj.allAdSetCount || 0);
		   if (obj.adSetName && obj.adSetName != ""){
			   adsetNameShow = obj.adSetName + '(' + adsetNameShow + ')';
		   }
		   //广告显示
		   var adgroupNameShow = (obj.adGroupCount || 0) + '/' + (obj.allAdGroupCount || 0);
		   if (obj.adName && obj.adName != ""){
			   adgroupNameShow = obj.adName + '(' + adgroupNameShow + ')';
		   }

			tmpHtml += '</td>'
					+ '<td title="'+campaignNameShow+'" class="number-show">'
					+ campaignNameShow
					+ '</td>'
					+ '<td title="'+adsetNameShow+'" class="number-show">'
		            + adsetNameShow
					+ '</td>'
					+ '<td title="'+adgroupNameShow+'" class="number-show">'
					+ adgroupNameShow
					+ '</td>'
					+ '<td title="'+(obj.creativeCount || 0)+'/'+(obj.allCreativeCount || 0)+'" class="number-show">'
					+ (obj.creativeCount || 0)
					+ '/'
					+ (obj.allCreativeCount || 0)
					+ '</td>'
//					+ '<td title="'+ budgetHtml +'">'
//					+ budgetHtml
//					+ '</td>'
					+ '<td title="'+timeHtml+'" class="number-show"-show>'
					+ timeHtml
					+ '<span class="list-timezone number-show">'+(obj.timezone || '')+'</span>'
					+ '</td>'
					+ '</tr>';

			return tmpHtml;
		}
        /**
         *  重试事件 add by evan 2015-07-12
         */
        ,bindRetry : function(){
            var _this = this;
            //渲染弹出框
            var retryModal= $('#retry-modal'),
           		confirmAction = $('button[confirm]', retryModal);
            retryModal.modal({
                backdrop: 'static',
                keyboard: false,
                show: false
            });

            var _batchId,_tr;
            //绑定重试事件
            $('.publish-batch-list').off('click', '.glyphicon-repeat');
            $('.publish-batch-list').on('click', '.glyphicon-repeat', function(){
                var _retryAction = $(this);
                _tr = _retryAction.closest('tr');
                _batchId = _tr.attr('batch-id');
				retryModal.modal('show');
            });
			//绑定确定提交事件
            confirmAction.unbind('click');
            confirmAction.bind('click', function(){
            	confirmRetry(function(){
            		retryModal.modal('hide')
            	});
            });
            function confirmRetry(cb){
            	var loadingArea = $('.modal-content', retryModal);
            	Kit.loading.show(loadingArea);
            	http.work('/publishbatchs/retry',_batchId,'POST').then(function(res){
            		if(res.flag == 'success'){
            			_tr.attr('class','p-ongoing');
            			Kit.alert_success(I18N.getText('adList','retrySucceed'));
            		}else{
            			Kit.alert2(I18N.getText('adList','retryFailed'));
            		}
                    _this.updataState();
                    cb();
            		Kit.loading.hide(loadingArea);
                });
            }
        }
        ,bindOpenDetail:function(){
        	$('table[list-manager="ad-list"] a[data-href]').off('click').on('click',function(e){
        		var url = window.top.location.origin+window.top.location.pathname+$(this).data('href');
        		console.log(url)
        		var win = window.open(url, '_blank');
        	});
        }
   }
   return AdList;
});
